package com.ido.otaclient.adapter;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 该 PagerAdapter 的实现将只保留当前页面，当页面离开视线后，就会被消除，释放其资源；而在页面需要显示时，生成新的页面
 */

public class SimpleFragmentStatePagerAdapter extends FragmentStatePagerAdapter {

    private List<Fragment> pagers = new ArrayList<>();
    private String[] titles;


    public SimpleFragmentStatePagerAdapter(FragmentManager fm, List<Fragment> pagers)  {
        super(fm);
        this.pagers.clear();
        this.pagers.addAll(pagers);
    }

    public SimpleFragmentStatePagerAdapter(FragmentManager fm, List<Fragment> pagers, String[] titles)  {
        super(fm);
        this.pagers.clear();
        this.pagers.addAll(pagers);
        this.titles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return isNull(pagers) ? null : pagers.get(position);
    }

    @Override
    public int getCount() {
        return isNull(pagers) ? 0 : pagers.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return isNull(pagers) ? null : (isNull(titles) ? null : titles[position]);
    }

    @Override
    public int getItemPosition(Object object) {
        return isNull(pagers) ? -1 : pagers.indexOf(object);
    }

    private boolean isNull(Object obj){
        return obj == null;
    }
}
